<template>
  <div class="min-h-screen py-8 px-4 sm:px-6 lg:px-8">
    <div class="max-w-7xl mx-auto">
      <!-- 页面标题 -->
      <div class="text-center mb-12">
        <h1 class="text-4xl font-bold mb-4 tech-text">Media Capabilities API</h1>
        <p class="text-gray-300 text-lg">
          查询浏览器的媒体解码和编码能力，优化媒体播放体验
        </p>
      </div>

      <!-- 浏览器支持提示 -->
      <div v-if="!isSupported" class="tech-card mb-8 border-yellow-600">
        <div class="flex items-center mb-4">
          <i class="i-carbon-warning text-yellow-500 text-xl mr-3"></i>
          <h3 class="text-xl font-semibold text-yellow-500">浏览器支持提示</h3>
        </div>
        <p class="text-gray-300">
          您的浏览器不支持 Media Capabilities API。此功能需要 Chrome 66+, Firefox 63+, Safari 13+ 或其他支持该 API 的浏览器。
        </p>
      </div>

      <!-- 快速测试 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">快速测试</h2>
        <p class="text-gray-300 mb-6">点击下方按钮快速测试常见媒体格式</p>
        
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
          <button
            @click="testPreset('1080p-h264')"
            class="tech-button"
          >
            <i class="i-carbon-video mr-2"></i>
            1080p H.264
          </button>
          <button
            @click="testPreset('4k-vp9')"
            class="tech-button"
          >
            <i class="i-carbon-video-filled mr-2"></i>
            4K VP9
          </button>
          <button
            @click="testPreset('8k-av1')"
            class="tech-button"
          >
            <i class="i-carbon-hd mr-2"></i>
            8K AV1
          </button>
          <button
            @click="testPreset('aac-audio')"
            class="tech-button"
          >
            <i class="i-carbon-music mr-2"></i>
            AAC 音频
          </button>
        </div>
      </div>

      <!-- 视频解码测试 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">视频解码能力测试</h2>
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div class="space-y-4">
            <div>
              <label class="text-white font-medium mb-2 block">编解码器</label>
              <select
                v-model="videoConfig.codec"
                class="w-full bg-gray-800 text-white px-4 py-3 rounded-lg border border-gray-700 focus:border-tech-accent outline-none"
              >
                <option value="video/mp4; codecs=avc1.42E01E">H.264 (AVC) Baseline</option>
                <option value="video/mp4; codecs=avc1.4D401E">H.264 (AVC) Main</option>
                <option value="video/mp4; codecs=avc1.64001E">H.264 (AVC) High</option>
                <option value="video/webm; codecs=vp8">VP8</option>
                <option value="video/webm; codecs=vp9">VP9</option>
                <option value="video/mp4; codecs=hev1.1.6.L93.B0">H.265 (HEVC)</option>
                <option value="video/mp4; codecs=av01.0.05M.08">AV1</option>
              </select>
            </div>

            <div>
              <label class="text-white font-medium mb-2 block">分辨率</label>
              <select
                v-model="videoConfig.resolution"
                class="w-full bg-gray-800 text-white px-4 py-3 rounded-lg border border-gray-700 focus:border-tech-accent outline-none"
              >
                <option value="640x480">640x480 (SD)</option>
                <option value="1280x720">1280x720 (HD)</option>
                <option value="1920x1080">1920x1080 (Full HD)</option>
                <option value="2560x1440">2560x1440 (2K)</option>
                <option value="3840x2160">3840x2160 (4K)</option>
                <option value="7680x4320">7680x4320 (8K)</option>
              </select>
            </div>

            <div>
              <label class="text-white font-medium mb-2 block">帧率 (fps)</label>
              <input
                v-model.number="videoConfig.framerate"
                type="number"
                min="1"
                max="120"
                class="w-full bg-gray-800 text-white px-4 py-3 rounded-lg border border-gray-700 focus:border-tech-accent outline-none"
              >
            </div>

            <div>
              <label class="text-white font-medium mb-2 block">比特率 (bps)</label>
              <input
                v-model.number="videoConfig.bitrate"
                type="number"
                min="100000"
                max="100000000"
                step="100000"
                class="w-full bg-gray-800 text-white px-4 py-3 rounded-lg border border-gray-700 focus:border-tech-accent outline-none"
              >
            </div>
          </div>

          <div class="space-y-4">
            <button
              @click="testVideoDecoding"
              :disabled="!isSupported || isTestingVideo"
              class="tech-button w-full disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <i class="i-carbon-play mr-2"></i>
              {{ isTestingVideo ? '测试中...' : '测试视频解码' }}
            </button>

            <div v-if="videoResult" class="bg-gray-800 rounded-lg p-6">
              <h3 class="text-white font-semibold mb-4 flex items-center">
                <i
                  :class="videoResult.supported ? 'i-carbon-checkmark-filled text-green-400' : 'i-carbon-close-filled text-red-400'"
                  class="text-xl mr-2"
                ></i>
                测试结果
              </h3>

              <div class="space-y-3 text-sm">
                <div class="flex justify-between">
                  <span class="text-gray-400">支持解码:</span>
                  <span :class="videoResult.supported ? 'text-green-400' : 'text-red-400'" class="font-semibold">
                    {{ videoResult.supported ? '✓ 支持' : '✗ 不支持' }}
                  </span>
                </div>

                <div class="flex justify-between">
                  <span class="text-gray-400">流畅播放:</span>
                  <span :class="videoResult.smooth ? 'text-green-400' : 'text-yellow-400'" class="font-semibold">
                    {{ videoResult.smooth ? '✓ 流畅' : '⚠ 可能卡顿' }}
                  </span>
                </div>

                <div class="flex justify-between">
                  <span class="text-gray-400">电源效率:</span>
                  <span :class="videoResult.powerEfficient ? 'text-green-400' : 'text-yellow-400'" class="font-semibold">
                    {{ videoResult.powerEfficient ? '✓ 高效' : '⚠ 耗电' }}
                  </span>
                </div>

                <div v-if="videoResult.decodingInfo" class="pt-3 border-t border-gray-700">
                  <div class="text-gray-400 mb-2">详细信息:</div>
                  <pre class="text-xs text-gray-300 bg-gray-900 p-3 rounded overflow-x-auto">{{ JSON.stringify(videoResult.decodingInfo, null, 2) }}</pre>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 音频解码测试 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">音频解码能力测试</h2>
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div class="space-y-4">
            <div>
              <label class="text-white font-medium mb-2 block">编解码器</label>
              <select
                v-model="audioConfig.codec"
                class="w-full bg-gray-800 text-white px-4 py-3 rounded-lg border border-gray-700 focus:border-tech-accent outline-none"
              >
                <option value="audio/mp4; codecs=mp4a.40.2">AAC</option>
                <option value="audio/mpeg">MP3</option>
                <option value="audio/webm; codecs=opus">Opus</option>
                <option value="audio/webm; codecs=vorbis">Vorbis</option>
                <option value="audio/flac">FLAC</option>
                <option value="audio/wav">WAV (PCM)</option>
              </select>
            </div>

            <div>
              <label class="text-white font-medium mb-2 block">声道数</label>
              <select
                v-model.number="audioConfig.channels"
                class="w-full bg-gray-800 text-white px-4 py-3 rounded-lg border border-gray-700 focus:border-tech-accent outline-none"
              >
                <option :value="1">单声道 (Mono)</option>
                <option :value="2">立体声 (Stereo)</option>
                <option :value="6">5.1 环绕声</option>
                <option :value="8">7.1 环绕声</option>
              </select>
            </div>

            <div>
              <label class="text-white font-medium mb-2 block">采样率 (Hz)</label>
              <select
                v-model.number="audioConfig.samplerate"
                class="w-full bg-gray-800 text-white px-4 py-3 rounded-lg border border-gray-700 focus:border-tech-accent outline-none"
              >
                <option :value="44100">44100 (CD 质量)</option>
                <option :value="48000">48000 (DVD 质量)</option>
                <option :value="96000">96000 (高清)</option>
                <option :value="192000">192000 (超高清)</option>
              </select>
            </div>

            <div>
              <label class="text-white font-medium mb-2 block">比特率 (bps)</label>
              <input
                v-model.number="audioConfig.bitrate"
                type="number"
                min="64000"
                max="320000"
                step="1000"
                class="w-full bg-gray-800 text-white px-4 py-3 rounded-lg border border-gray-700 focus:border-tech-accent outline-none"
              >
            </div>
          </div>

          <div class="space-y-4">
            <button
              @click="testAudioDecoding"
              :disabled="!isSupported || isTestingAudio"
              class="tech-button w-full disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <i class="i-carbon-play mr-2"></i>
              {{ isTestingAudio ? '测试中...' : '测试音频解码' }}
            </button>

            <div v-if="audioResult" class="bg-gray-800 rounded-lg p-6">
              <h3 class="text-white font-semibold mb-4 flex items-center">
                <i
                  :class="audioResult.supported ? 'i-carbon-checkmark-filled text-green-400' : 'i-carbon-close-filled text-red-400'"
                  class="text-xl mr-2"
                ></i>
                测试结果
              </h3>

              <div class="space-y-3 text-sm">
                <div class="flex justify-between">
                  <span class="text-gray-400">支持解码:</span>
                  <span :class="audioResult.supported ? 'text-green-400' : 'text-red-400'" class="font-semibold">
                    {{ audioResult.supported ? '✓ 支持' : '✗ 不支持' }}
                  </span>
                </div>

                <div class="flex justify-between">
                  <span class="text-gray-400">流畅播放:</span>
                  <span :class="audioResult.smooth ? 'text-green-400' : 'text-yellow-400'" class="font-semibold">
                    {{ audioResult.smooth ? '✓ 流畅' : '⚠ 可能卡顿' }}
                  </span>
                </div>

                <div class="flex justify-between">
                  <span class="text-gray-400">电源效率:</span>
                  <span :class="audioResult.powerEfficient ? 'text-green-400' : 'text-yellow-400'" class="font-semibold">
                    {{ audioResult.powerEfficient ? '✓ 高效' : '⚠ 耗电' }}
                  </span>
                </div>

                <div v-if="audioResult.decodingInfo" class="pt-3 border-t border-gray-700">
                  <div class="text-gray-400 mb-2">详细信息:</div>
                  <pre class="text-xs text-gray-300 bg-gray-900 p-3 rounded overflow-x-auto">{{ JSON.stringify(audioResult.decodingInfo, null, 2) }}</pre>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 批量测试 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">批量格式测试</h2>
        <p class="text-gray-300 mb-6">测试多种常见媒体格式的支持情况</p>
        
        <button
          @click="runBatchTest"
          :disabled="!isSupported || isBatchTesting"
          class="tech-button mb-6 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          <i class="i-carbon-play-filled mr-2"></i>
          {{ isBatchTesting ? '测试中...' : '开始批量测试' }}
        </button>

        <div v-if="batchResults.length > 0" class="overflow-x-auto">
          <table class="w-full">
            <thead>
              <tr class="border-b border-gray-700">
                <th class="text-left py-3 px-4 text-gray-400 font-medium">格式</th>
                <th class="text-left py-3 px-4 text-gray-400 font-medium">分辨率</th>
                <th class="text-left py-3 px-4 text-gray-400 font-medium">支持</th>
                <th class="text-left py-3 px-4 text-gray-400 font-medium">流畅</th>
                <th class="text-left py-3 px-4 text-gray-400 font-medium">省电</th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="(result, index) in batchResults"
                :key="index"
                class="border-b border-gray-800 hover:bg-gray-800/50 transition-colors"
              >
                <td class="py-3 px-4 text-white">{{ result.name }}</td>
                <td class="py-3 px-4 text-gray-300">{{ result.resolution }}</td>
                <td class="py-3 px-4">
                  <span :class="result.supported ? 'text-green-400' : 'text-red-400'">
                    {{ result.supported ? '✓' : '✗' }}
                  </span>
                </td>
                <td class="py-3 px-4">
                  <span :class="result.smooth ? 'text-green-400' : 'text-yellow-400'">
                    {{ result.smooth ? '✓' : '⚠' }}
                  </span>
                </td>
                <td class="py-3 px-4">
                  <span :class="result.powerEfficient ? 'text-green-400' : 'text-yellow-400'">
                    {{ result.powerEfficient ? '✓' : '⚠' }}
                  </span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- API 信息 -->
      <div class="tech-card">
        <h3 class="text-xl font-semibold mb-4 text-white">API 信息</h3>
        <div class="space-y-4 text-gray-300">
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">浏览器支持</h4>
            <p>Chrome 66+, Firefox 63+, Safari 13+, Edge 79+</p>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">主要方法</h4>
            <ul class="list-disc list-inside space-y-1">
              <li><code class="bg-gray-800 px-2 py-1 rounded">navigator.mediaCapabilities.decodingInfo()</code> - 查询解码能力</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">navigator.mediaCapabilities.encodingInfo()</code> - 查询编码能力</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">返回信息</h4>
            <ul class="list-disc list-inside space-y-1">
              <li><code class="bg-gray-800 px-2 py-1 rounded">supported</code> - 是否支持该格式</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">smooth</code> - 是否能流畅播放</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">powerEfficient</code> - 是否节能（硬件加速）</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">使用场景</h4>
            <ul class="list-disc list-inside space-y-1">
              <li>自适应流媒体播放器（根据设备能力选择最佳格式）</li>
              <li>视频会议应用（选择最优编解码器）</li>
              <li>媒体转码服务（确定支持的格式）</li>
              <li>性能优化（使用硬件加速格式）</li>
              <li>用户体验改善（避免不支持的格式）</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">与其他 API 的区别</h4>
            <p class="text-sm leading-relaxed">
              与 <code class="bg-gray-800 px-2 py-1 rounded">HTMLMediaElement.canPlayType()</code> 不同，
              Media Capabilities API 不仅告诉你浏览器是否支持某种格式，还会告诉你播放效果如何。
              它提供了更详细的信息，包括是否流畅、是否节能等，帮助开发者做出更好的决策。
            </p>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">最佳实践</h4>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li>优先选择 <code class="bg-gray-800 px-1 rounded">powerEfficient: true</code> 的格式以延长电池续航</li>
              <li>在移动设备上避免使用不流畅的高分辨率格式</li>
              <li>根据网络状况和设备能力动态调整视频质量</li>
              <li>缓存测试结果以避免重复查询</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

// 类型定义
interface VideoConfig {
  codec: string
  resolution: string
  framerate: number
  bitrate: number
}

interface AudioConfig {
  codec: string
  channels: number
  samplerate: number
  bitrate: number
}

interface TestResult {
  supported: boolean
  smooth: boolean
  powerEfficient: boolean
  decodingInfo?: any
}

interface BatchResult {
  name: string
  resolution: string
  supported: boolean
  smooth: boolean
  powerEfficient: boolean
}

// 响应式状态
const isSupported = ref('mediaCapabilities' in navigator)
const isTestingVideo = ref(false)
const isTestingAudio = ref(false)
const isBatchTesting = ref(false)

// 配置
const videoConfig = ref<VideoConfig>({
  codec: 'video/mp4; codecs=avc1.42E01E',
  resolution: '1920x1080',
  framerate: 30,
  bitrate: 5000000
})

const audioConfig = ref<AudioConfig>({
  codec: 'audio/mp4; codecs=mp4a.40.2',
  channels: 2,
  samplerate: 48000,
  bitrate: 128000
})

// 结果
const videoResult = ref<TestResult | null>(null)
const audioResult = ref<TestResult | null>(null)
const batchResults = ref<BatchResult[]>([])

// 测试视频解码
const testVideoDecoding = async () => {
  if (!isSupported.value) return

  isTestingVideo.value = true
  videoResult.value = null

  try {
    const [width, height] = videoConfig.value.resolution.split('x').map(Number)

    const configuration = {
      type: 'file' as const,
      video: {
        contentType: videoConfig.value.codec,
        width,
        height,
        bitrate: videoConfig.value.bitrate,
        framerate: videoConfig.value.framerate
      }
    }

    const result = await navigator.mediaCapabilities.decodingInfo(configuration)

    videoResult.value = {
      supported: result.supported,
      smooth: result.smooth,
      powerEfficient: result.powerEfficient,
      decodingInfo: result
    }

  } catch (err) {
    console.error('视频解码测试失败:', err)
    videoResult.value = {
      supported: false,
      smooth: false,
      powerEfficient: false
    }
  } finally {
    isTestingVideo.value = false
  }
}

// 测试音频解码
const testAudioDecoding = async () => {
  if (!isSupported.value) return

  isTestingAudio.value = true
  audioResult.value = null

  try {
    const configuration = {
      type: 'file' as const,
      audio: {
        contentType: audioConfig.value.codec,
        channels: audioConfig.value.channels,
        bitrate: audioConfig.value.bitrate,
        samplerate: audioConfig.value.samplerate
      }
    }

    const result = await navigator.mediaCapabilities.decodingInfo(configuration)

    audioResult.value = {
      supported: result.supported,
      smooth: result.smooth,
      powerEfficient: result.powerEfficient,
      decodingInfo: result
    }

  } catch (err) {
    console.error('音频解码测试失败:', err)
    audioResult.value = {
      supported: false,
      smooth: false,
      powerEfficient: false
    }
  } finally {
    isTestingAudio.value = false
  }
}

// 预设测试
const testPreset = async (preset: string) => {
  const presets: Record<string, any> = {
    '1080p-h264': {
      codec: 'video/mp4; codecs=avc1.42E01E',
      resolution: '1920x1080',
      framerate: 30,
      bitrate: 5000000
    },
    '4k-vp9': {
      codec: 'video/webm; codecs=vp9',
      resolution: '3840x2160',
      framerate: 60,
      bitrate: 20000000
    },
    '8k-av1': {
      codec: 'video/mp4; codecs=av01.0.05M.08',
      resolution: '7680x4320',
      framerate: 60,
      bitrate: 50000000
    },
    'aac-audio': {
      codec: 'audio/mp4; codecs=mp4a.40.2',
      channels: 2,
      samplerate: 48000,
      bitrate: 128000
    }
  }

  const config = presets[preset]
  
  if (config.resolution) {
    // 视频测试
    videoConfig.value = config
    await testVideoDecoding()
  } else {
    // 音频测试
    audioConfig.value = config
    await testAudioDecoding()
  }
}

// 批量测试
const runBatchTest = async () => {
  if (!isSupported.value) return

  isBatchTesting.value = true
  batchResults.value = []

  const testConfigs = [
    { name: 'H.264 720p', codec: 'video/mp4; codecs=avc1.42E01E', resolution: '1280x720', bitrate: 2500000 },
    { name: 'H.264 1080p', codec: 'video/mp4; codecs=avc1.42E01E', resolution: '1920x1080', bitrate: 5000000 },
    { name: 'H.264 4K', codec: 'video/mp4; codecs=avc1.42E01E', resolution: '3840x2160', bitrate: 20000000 },
    { name: 'VP8 720p', codec: 'video/webm; codecs=vp8', resolution: '1280x720', bitrate: 2500000 },
    { name: 'VP9 1080p', codec: 'video/webm; codecs=vp9', resolution: '1920x1080', bitrate: 5000000 },
    { name: 'VP9 4K', codec: 'video/webm; codecs=vp9', resolution: '3840x2160', bitrate: 20000000 },
    { name: 'AV1 1080p', codec: 'video/mp4; codecs=av01.0.05M.08', resolution: '1920x1080', bitrate: 3000000 },
    { name: 'AV1 4K', codec: 'video/mp4; codecs=av01.0.05M.08', resolution: '3840x2160', bitrate: 15000000 },
    { name: 'H.265 1080p', codec: 'video/mp4; codecs=hev1.1.6.L93.B0', resolution: '1920x1080', bitrate: 4000000 },
    { name: 'H.265 4K', codec: 'video/mp4; codecs=hev1.1.6.L93.B0', resolution: '3840x2160', bitrate: 15000000 }
  ]

  for (const config of testConfigs) {
    try {
      const [width, height] = config.resolution.split('x').map(Number)

      const configuration = {
        type: 'file' as const,
        video: {
          contentType: config.codec,
          width,
          height,
          bitrate: config.bitrate,
          framerate: 30
        }
      }

      const result = await navigator.mediaCapabilities.decodingInfo(configuration)

      batchResults.value.push({
        name: config.name,
        resolution: config.resolution,
        supported: result.supported,
        smooth: result.smooth,
        powerEfficient: result.powerEfficient
      })

      // 添加小延迟以避免过快
      await new Promise(resolve => setTimeout(resolve, 100))

    } catch (err) {
      console.error(`测试失败: ${config.name}`, err)
      batchResults.value.push({
        name: config.name,
        resolution: config.resolution,
        supported: false,
        smooth: false,
        powerEfficient: false
      })
    }
  }

  isBatchTesting.value = false
}
</script>

